import {isObject} from "../utils/util";

export default class Agency {
    constructor() {
        this.vm = this.getWxMethods()
        this.routerConfig=[]
        this.initProxy()
    }

    getWxMethods() {
        let vm = {}
        Object.keys(wx).forEach(x => {
            vm[x] = wx[x]
        })
        return wx = vm;
    }

    initProxy() {
        this.proxyRouter()
        // console.log(this.vm)
    }
    setRouterBefore(data){
        this.routerConfig.push(data)
    }
    setRouterAfter(data){
        this.routerConfig.push(data)
    }
    //路由代理
    proxyRouter(config = {}) {
        const that = this;
        const routers = ['switchTab', 'reLaunch', 'redirectTo', 'navigateTo', 'navigateBack'];
        routers.forEach(method => {
            const originalMethod = wx[method]; // 保存原方法以便后续调用

            wx[method] = function (data) {
                const currentPage = getCurrentPages().pop(); // 获取当前页面实例

                // 执行页面级的路由前置钩子
                const pageBeforeHook = currentPage.$beforeRouter?.({ data, routerType: method, beforePage: currentPage });
                if (pageBeforeHook === false) return; // 如果页面级钩子阻止了路由跳转，则终止执行
                if (isObject(pageBeforeHook)) {
                    data = { ...data, ...pageBeforeHook.data }; // 合并页面级钩子修改的data
                }
                if(!data) data={}
                // 准备代理的成功回调
                const originalSuccess = data.success;
                data.success = function (...args) {
                    // 延迟执行，确保页面已切换
                    setTimeout(() => {
                        const newPage = getCurrentPages().pop(); // 获取新的当前页面实例
                        // 执行全局配置的路由后置钩子
                        that.routerConfig.forEach(config => {
                            config.succeed?.(newPage, method);
                        });
                    }, 300);

                    // 调用原始的成功回调
                    if (typeof originalSuccess === 'function') {
                        originalSuccess.apply(this, args);
                    }
                };

                // 执行全局配置的路由前置钩子
                for (const config of that.routerConfig) {
                    if (config.before) {
                        const beforeHookResult = config.before({ data, routerType: method, beforePage: currentPage });
                        if (beforeHookResult === false) return; // 如果前置钩子阻止了路由跳转，则终止执行
                        if (isObject(beforeHookResult)) {
                            data = { ...data, ...beforeHookResult.data }; // 合并全局前置钩子修改的data
                        }
                    }
                }

                // 调用原始路由方法
                originalMethod.call(wx, data);
            };
        });
    }

}